﻿<%@ WebHandler Language="C#" Class="BomChangeErpConfirmPageHandler" %>

/* Description: 工艺更换集件校准
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2025.9.24
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using System.Web.SessionState;
using Newtonsoft.Json;
using System.Collections;
using System.IO;
using System.Configuration;

public class BomChangeErpConfirmPageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    string exportPath = ConfigurationManager.AppSettings["ExportPath"]; //导出路径
    string fileBasePath = ConfigurationManager.AppSettings["ImportPath"].ToString();//导入临时路径
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getUserInfo":
                    getUserInfo(context);
                    break;
                case "getContainerInfo":
                    getContainerInfo(context);
                    break;
                case "getCurrentBom":
                    getCurrentBom(context);//当前工艺集件信息
                    break;
                case "getHistoryBom":
                    getHistoryBom(context);//历史工艺集件信息
                    break;
                case "getDiff":
                    getDiff(context);//集件差异
                    break;
                case "resendData":
                    resendData(context);//重推
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
        }
    }

    void getContainerInfo(HttpContext context)
    {
        string sql = @"
SELECT DISTINCT mfg.mfgorderid,mfg.mfgordername,mfg.qty mfgqty,cci.containername,cci.qty,cci.workflowname || ':' || cci.workflowrevision workflowinfo,cci.workflowstepname,
       DECODE(cci.containertype,2,'批量加工',3,'批量带子序号') containertype,cci.plannedstartdate,cci.plannedcompletiondate,cci.workflowid,c.originalqty,cci.containerid
FROM containercurrentinfo cci
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN orderstatus od ON mfg.orderstatusid = od.orderstatusid
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
INNER JOIN bom b ON b.workflowid = cci.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
WHERE cci.containertype <> '7' AND c.originalqty = mfg.qty
      AND cci.isinstore = 0
      AND NVL(od.orderstatusname,'打开') <> '关闭'";
        //件号
        if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname LIKE '%{0}%'", context.Request["productname"].ToString());
        }

        //订单号
        if (context.Request["mfgordername"] != null && context.Request["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND mfg.mfgordername LIKE '%{0}%'", context.Request["mfgordername"].ToString());
        }

        //主制分厂
        if (context.Request["factoryid"] != null && context.Request["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND mfg.factoryid = '{0}'", context.Request["factoryid"].ToString());
        }

        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
        paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataColumn col in result.DBTable.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void getCurrentBom(HttpContext context)
    {
        string sql = @"
SELECT s.specno,s.opdesc specname,pbn.productname,pml.qtyrequired * c.originalqty qty
FROM containercurrentinfo cci
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN workflow wf ON wf.workflowid = cci.workflowid
--bom信息
INNER JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
--bom工序信息
LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid, pml.specid)
LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
--子零件信息
LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
WHERE cci.containerid = '{0}'
ORDER BY s.specno,pbn.productname";
        sql = string.Format(sql, context.Request.Form["containerid"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "成功", DBTable = dtBom }));
    }

    //历史工艺集件信息
    void getHistoryBom(HttpContext context)
    {
        string sql = @"
SELECT erp.specno,erp.specname,erp.productname,erp.qty 
FROM erp_send_material erp 
WHERE erp.mfgordername = '{0}' 
ORDER BY erp.specno,erp.productname";
        sql = string.Format(sql, context.Request.Form["mfgordername"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "成功", DBTable = dtBom }));
    }

    void getDiff(HttpContext context)
    {
        //        string containerid = context.Request.Form["containerid"].ToString();
        //        string mfgordername = context.Request.Form["mfgordername"].ToString();
        //        string sql = @"
        //--以新的为基准
        //SELECT cci.mfgordername,pbn.productname,erp.productbatchno,s.specno,s.opdesc specname,
        //       pml.qtyrequired * c.originalqty - NVL(erp.qty,0) diffqty,
        //       CASE WHEN erp.id IS NULL THEN '增加条目'
        //            WHEN erp.id IS NOT NULL AND erp.qty > (pml.qtyrequired * c.originalqty) THEN '减少数量' 
        //            WHEN erp.id IS NOT NULL AND erp.qty < (pml.qtyrequired * c.originalqty) THEN '增加数量' 
        //            WHEN erp.id IS NOT NULL AND erp.qty = (pml.qtyrequired * c.originalqty) THEN '无差异'
        //       END oper_type,b.bomid
        //FROM containercurrentinfo cci
        //LEFT JOIN container c ON c.containerid = cci.containerid
        //LEFT JOIN workflow wf ON wf.workflowid = cci.workflowid
        //--bom信息
        //LEFT JOIN bom b ON b.workflowid = wf.workflowid
        //LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
        //LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
        //--bom工序信息
        //LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
        //LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid, pml.specid)
        //LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
        //--子零件信息
        //LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
        //LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
        //LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
        //LEFT JOIN erp_send_material erp ON erp.mfgordername = cci.mfgordername AND erp.productname = pbn.productname AND erp.specno = s.specno
        //WHERE cci.containerid = '{0}'
        //
        //UNION ALL
        //
        //SELECT erp.mfgordername,erp.productname,erp.productbatchno,
        //       erp.specno,erp.specname,
        //       -erp.qty diffqty,
        //       '删除条目' oper_type,'' bomid
        //FROM erp_send_material erp
        //LEFT JOIN (
        //    SELECT cci.mfgordername,pbn.productname,s.specno
        //    FROM containercurrentinfo cci
        //    LEFT JOIN container c ON c.containerid = cci.containerid
        //    LEFT JOIN workflow wf ON wf.workflowid = cci.workflowid
        //    --bom信息
        //    LEFT JOIN bom b ON b.workflowid = wf.workflowid
        //    LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
        //    LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
        //    --bom工序信息
        //    LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
        //    LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid, pml.specid)
        //    LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
        //    --子零件信息
        //    LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
        //    LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
        //    LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
        //    WHERE cci.containerid = '{0}'
        //) t ON t.mfgordername = erp.mfgordername AND t.productname = erp.productname AND t.specno = erp.specno
        //WHERE erp.mfgordername = '{1}' AND t.productname IS NULL";
        //        sql = string.Format(sql, containerid, mfgordername);
        //        DataTable dtDiff = DatabaseHelper.Query_ReturnDatTable(sql);
        //        foreach (DataColumn col in dtDiff.Columns)
        //        {
        //            col.ColumnName = col.ColumnName.ToLower();
        //        }
        //        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "成功", DBTable = dtDiff }));
        string mfgordername = context.Request.Form["mfgordername"].ToString();
        string sql = @"
SELECT t.id,t.specno,t.specname,t.productname,t.diffqty,t.mfgordername,
       DECODE(t.oper_type,1,'增加数量',2,'减少数量',3,'增加条目',4,'删除条目') oper_type,t.erp_return_date,t.createdate,'已推送' send_status,
       DECODE(t.erp_status,0,'失败',1,'成功') erp_status,t.erp_msg
FROM erp_mes_bom_diff t
WHERE t.mfgordername = '{0}' AND t.diff_type = 'MES'";
        sql = string.Format(sql, mfgordername);
        DataTable dtDiff = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtDiff.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "成功", DBTable = dtDiff }));
    }

    void getUserInfo(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", ReturnData = m_UserInfo }));
        }
    }

    void resendData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
            return;
        }
        string mfgordername = context.Request.Form["mfgordername"].ToString();
        string containerid = context.Request.Form["containerid"].ToString();
        string sql = @"
SELECT * FROM mes_send_erp_diff t WHERE t.issend = 0 AND t.mfgordername = '{0}' AND t.containerid = '{1}' AND t.diff_type = 'MES'
";
        sql = string.Format(sql, mfgordername, containerid);
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dt.Rows.Count == 0)
        {
            string insertSql = @"INSERT INTO mes_send_erp_diff(mfgordername,containerid,diff_type) VALUES('{0}','{1}','MES')";
            insertSql = string.Format(insertSql, mfgordername, containerid);
            int count = DatabaseHelper.ExecuteSql(insertSql);
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = count > 0, Message = count > 0 ? "重推成功" : "重推失败", ReturnData = null }));
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "重推失败", ReturnData = null }));
        }
    }
}